<!-- 车辆维护 -->
<template>
  <view class="content">
    <u-form :model="form" ref="uForm" :label-width="240">
      <view class="card-box">
        <view class="u-flex"
          >行驶证<view class="card-icon-box">
            <view></view>
            <view></view> </view
        ></view>
        <view class="u-flex top-box">
          <u-form-item class="width-50" label-position="top">
            <!-- label="车头行驶证"
            left-icon="star-fill"
            :left-icon-style="{
              color: 'red',
              'font-size': '18rpx',
            }" -->
            <u-upload
              :upload-text="'添加车头行驶证'"
              :width="310"
              :height="190"
              class="uUpload-box"
              ref="uUpload1"
              :action="uploadUrl"
              @on-success="headLicensesuccess"
              @on-remove="headLicenseremove"
              @on-error="testerror"
              :show-progress="form.headLicense ? false : true"
              max-count="1"
              :form-data="uploaderData1"
            >
            </u-upload>
            <image
              v-if="headLicense"
              :src="uploadIconList[0].icon"
              style="
                width: 40rpx;
                height: 40rpx;
                display: inline;
                position: absolute;
                bottom: 30rpx;
                right: 20rpx;
              "
            />
          </u-form-item>
          <u-form-item class="width-50" label-position="top">
            <!-- label="挂车行驶证"
            left-icon="star-fill"
            :left-icon-style="{
              color: 'red',
              'font-size': '18rpx',
            }" -->
            <u-upload
              :upload-text="'添加挂车行驶证'"
              :width="310"
              :height="190"
              class="uUpload-box"
              ref="uUpload2"
              :action="uploadUrl"
              @on-success="attachLicensesuccess"
              @on-remove="attachLicenseremove"
              @on-error="testerror"
              :show-progress="form.attachLicense ? false : true"
              max-count="1"
              :form-data="uploaderData2"
            ></u-upload>
            <image
              v-if="attachLicenseEditable"
              :src="uploadIconList[0].icon"
              style="
                width: 40rpx;
                height: 40rpx;
                display: inline;
                position: absolute;
                bottom: 30rpx;
                right: 20rpx;
              "
            />
          </u-form-item>
        </view>
        <u-form-item
          label="车头车牌号"
          ref="carNo"
          prop="carNo"
          class="form-item-box"
          left-icon="star-fill"
          :left-icon-style="{
            color: 'red',
            'font-size': '18rpx',
          }"
        >
          <u-input
            v-model="form.carNo"
            maxlength="8"
            placeholder="请输入车头车牌号"
            @on-blur="upperCase"
            :disabled="!headLicense"
          />
        </u-form-item>
        <u-form-item
          label="挂车车牌号"
          prop="attachNo"
          ref="attachNo"
          class="form-item-box"
          left-icon="star-fill"
          :left-icon-style="{
            color: 'red',
            'font-size': '18rpx',
          }"
        >
          <u-input
            v-model="form.attachNo"
            maxlength="8"
            placeholder="请输入挂车车牌号"
            @on-blur="upperCase"
            :disabled="!attachLicenseEditable"
          />
        </u-form-item>
      </view>
      <view class="card-box">
        <view class="u-flex"
          >道路运输证<view class="card-icon-box">
            <view></view>
            <view></view> </view
        ></view>
        <view class="u-flex top-box">
          <u-form-item class="width-50" label-position="top">
            <!-- label="车头运输证" left-icon="star-fill" :left-icon-style="{ color:
            'red', 'font-size': '18rpx', }" -->
            <u-upload
              :upload-text="'添加车头运输证'"
              :width="310"
              :height="190"
              ref="uUpload3"
              :action="uploadUrl1"
              @on-success="headTranssuccess"
              @on-remove="headTransremove"
              @on-error="testerror"
              :show-progress="form.headTrans ? false : true"
              max-count="1"
              :form-data="uploaderData"
            ></u-upload>
            <image
              v-if="headTransEditable"
              :src="uploadIconList[0].icon"
              style="
                width: 40rpx;
                height: 40rpx;
                display: inline;
                position: absolute;
                bottom: 30rpx;
                right: 20rpx;
              "
            />
          </u-form-item>
          <u-form-item class="width-50" label-position="top">
            <!-- label="挂车运输证"
            left-icon="star-fill"
            :left-icon-style="{
              color: 'red',
              'font-size': '18rpx',
            }" -->
            <u-upload
              :upload-text="'添加挂车运输证'"
              :width="310"
              :height="190"
              ref="uUpload4"
              :action="uploadUrl1"
              @on-success="attachTranssuccess"
              @on-remove="attachTransremove"
              @on-error="testerror"
              :show-progress="form.attachTrans ? false : true"
              max-count="1"
              :form-data="uploaderData"
            ></u-upload>
            <image
              v-if="attachTransEditable"
              :src="uploadIconList[0].icon"
              style="
                width: 40rpx;
                height: 40rpx;
                display: inline;
                position: absolute;
                bottom: 30rpx;
                right: 20rpx;
              "
            />
          </u-form-item>
        </view>
      </view>
      <view class="card-box">
        <view class="u-flex"
          >附属资料<view class="card-icon-box">
            <view></view>
            <view></view> </view
        ></view>
        <div class="u-flex top-box">
          <u-form-item class="width-50" label-position="top">
            <!-- label="环保清单"
            left-icon="star-fill"
            :left-icon-style="{
              color: 'red',
              'font-size': '18rpx',
            }" -->
            <u-upload
              :upload-text="'添加环保清单'"
              :width="310"
              :height="190"
              ref="uUpload5"
              :action="uploadUrl1"
              @on-success="eProtectionSheetsuccess"
              @on-remove="eProtectionSheetremove"
              @on-error="testerror"
              :show-progress="form.eProtectionSheet ? false : true"
              max-count="1"
              :form-data="uploaderData"
            ></u-upload>
            <image
              v-if="eProtectionSheetEditable"
              :src="uploadIconList[0].icon"
              style="
                width: 40rpx;
                height: 40rpx;
                display: inline;
                position: absolute;
                bottom: 30rpx;
                right: 20rpx;
              "
            />
          </u-form-item>
          <u-form-item class="width-50" label-position="top">
            <!-- label="车辆照片"
            left-icon="star-fill"
            :left-icon-style="{
              color: 'red',
              'font-size': '18rpx',
            }" -->
            <u-upload
              :upload-text="'添加车辆照片'"
              :width="310"
              :height="190"
              ref="uUpload6"
              :action="uploadUrl1"
              @on-success="carPhotosuccess"
              @on-remove="carPhotoremove"
              @on-error="testerror"
              :show-progress="form.carPhoto ? false : true"
              max-count="1"
              :form-data="uploaderData"
            ></u-upload>
            <image
              v-if="carPhotoEditable"
              :src="uploadIconList[0].icon"
              style="
                width: 40rpx;
                height: 40rpx;
                display: inline;
                position: absolute;
                bottom: 30rpx;
                right: 20rpx;
              "
            />
          </u-form-item>
        </div>
        <u-form-item
          label="排放标准"
          prop="emissionName"
          class="form-item-box"
          left-icon="star-fill"
          :left-icon-style="{
            color: 'red',
            'font-size': '18rpx',
          }"
        >
          <u-input
            v-model="form.emissionName"
            type="select"
            @click="emissionStandardsShow = true"
            placeholder="请选择排放标准"
          />
          <u-select
            v-model="emissionStandardsShow"
            mode="single-column"
            :list="emissionStandardslist"
            @confirm="emissionStandardsconfirm"
          ></u-select>
        </u-form-item>
      </view>
    </u-form>
    <u-button
      type="primary"
      @click="validateRepeatBinding"
      class="vehiclemanagement-index-btn"
      >提交</u-button
    >
    <!-- 用来提示 -->
    <u-toast ref="uToast" />
    <!-- 审核不通过提示信息 -->
    <u-modal
      v-model="repeatBindingShow"
      :width="'600'"
      :showConfirmButton="false"
      :show-title="false"
    >
      <view style="font-weight: bold; padding: 10rpx 0 0 20rpx">系统提示</view>
      <image
        src="https://minio.wskjwl.com/uipicture/bell.png"
        style="width: 100rpx; height: 120rpx; margin-left: 40%"
      />
      <view style="text-align: center; margin: 60rpx 0 80rpx 0">
        <view>该车辆已被绑定</view>
        <view>确认后将无法获得新人福利</view>
      </view>
      <view
        style="
          display: flex;
          justify-content: space-around;
          margin-bottom: 20rpx;
        "
      >
        <u-button
          type="primary"
          shape="circle"
          plain
          style="width: 35%"
          @click="repeatBindingShow = false"
          >取 消
        </u-button>
        <u-button
          type="primary"
          shape="circle"
          style="width: 35%"
          @click="submit"
          >确 定
        </u-button>
      </view>
    </u-modal>
  </view>
</template>
<script>
import httpEnum from './../../common/httpEnum.js'
import { v_integer } from './../../common/util.js'
export default {
  data() {
    // 牌号验证
    const carNoRuls = async (rule, value, callback) => {
      let reg =
        /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$)|([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/
      // let reg = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/
      if (!value) {
        return callback(new Error('请输入车牌号'))
      } else if (!reg.test(value)) {
        return callback(new Error('请检查车牌号格式是否正确'))
      } else {
        callback()
      }
    }

    return {
      repeatBindingShow: false,
      headLicense: false,
      attachLicenseEditable: false,
      headTransEditable: false,
      attachTransEditable: false,
      eProtectionSheetEditable: false,
      carPhotoEditable: false,
      uploadUrl:
        httpEnum.baseUploadUrl +
        '/freight-business/ocr/recognize/vehicleLicense',
      uploadUrl1: httpEnum.baseUploadUrl + '/freight-business/file/app/upload',
      uploaderData1: {
        bucketName: 'app',
        folderName: 'photo',
        type: 1,
      },
      uploaderData2: {
        bucketName: 'app',
        folderName: 'photo',
        type: 2,
      },
      uploaderData: {
        bucketName: 'app',
        folderName: 'photo',
      },
      form: {
        carOwnerName: undefined, //车主姓名
        carOwnerMobile: undefined, //车主电话
        carNo: undefined, //车牌号
        attachNo: undefined, //挂车车牌号
        carType: undefined, //车型
        carTypeName: undefined, //车型1
        emissionName: undefined, //排放标准
        emission: undefined, //排放标准1
        fuelType: undefined, //燃料类型
        fuelTypeName: undefined, //燃料类型1
        carWeight: undefined, //车货总重
        axlNum: undefined, //轴数
        ascriptionType: '0',
        headLicense: undefined, //车头行驶证,
        attachLicense: undefined, //挂车行驶证,
        headTrans: undefined, //车头运输证,
        attachTrans: undefined, //挂车运输证,
        eProtectionSheet: undefined, //环保清单 ,
        carPhoto: undefined, //车辆照片 ,
      },
      carTypeShow: false,
      carTypelist: [
        {
          label: '前四后八',
          value: '1',
        },
        {
          label: '平板',
          value: '2',
        },
        {
          label: '六轴双驱',
          value: '3',
        },
        {
          label: '半挂牵引车',
          value: '4',
        },
        {
          label: '前四后四',
          value: '5',
        },
        {
          label: '中型自卸货车',
          value: '6',
        },
        {
          label: '六轴单驱',
          value: '7',
        },
      ],
      emissionStandardsShow: false,
      emissionStandardslist: [
        // {
        //   label: '国五',
        //   value: '1',
        // },
        // {
        //   label: '国六',
        //   value: '2',
        // },
        // {
        //   label: '其他',
        //   value: '3',
        // },
        // {
        //   label: '新能源',
        //   value: '4',
        // },
      ],
      fuelTypeShow: false,
      fuelTypelist: [],
      fuelTypelist1: [
        {
          label: '天然气',
          value: '1',
        },
        {
          label: '柴油',
          value: '2',
        },
        {
          label: '电动',
          value: '3',
        },
        {
          label: '汽油',
          value: '4',
        },
        {
          label: '其他',
          value: '5',
        },
      ],
      rules: {
        carOwnerName: [
          {
            required: true,
            message: '请输入车主姓名',
            // 可以单个或者同时写两个触发验证方式
            trigger: 'blur',
          },
        ],
        carOwnerMobile: [
          {
            required: true,
            message: '请输入车主电话',
            trigger: ['change', 'blur'],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          },
        ],
        carNo: [
          // { required: true, message: '请输入车牌号', trigger: 'blur' }

          {
            required: true,
            validator: carNoRuls,
            trigger: ['change', 'blur'],
          },
        ],
        attachNo: [
          // { required: true, message: '请输入车牌号', trigger: 'blur' }

          {
            required: true,
            validator: carNoRuls,
            trigger: ['change', 'blur'],
          },
        ],
        carTypeName: [
          {
            required: true,
            message: '请选择车型',
            trigger: ['change', 'blur'],
          },
        ],
        emissionName: [
          {
            required: true,
            message: '请选择排放标准',
            trigger: ['change', 'blur'],
          },
        ],
        fuelTypeName: [
          {
            required: true,
            message: '请选择燃料类型',
            trigger: ['change', 'blur'],
          },
        ],
        carWeight: [
          {
            required: true,
            validator: v_integer('请输入车货总重'),
            trigger: ['change', 'blur'],
          },
        ],
        axlNum: [
          {
            required: true,
            validator: v_integer('请输入轴数'),
            trigger: ['change', 'blur'],
          },
        ],
      },
      maxSize: 1024 * 1024 * 4,
      uploadIconList: [
        {
          icon: 'https://minio.wskjwl.com/uipicture/correcticon.png',
          path: '/pages/vehiclemanagement/vehiclemanagement',
          title: '完成标识',
        },
      ],
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  watch: {
    'form.carNo'(val, old) {
      this.upperCase(val)
    },
  },
  onShow() {
    this.getEmissionStandardsData()
  },
  mounted() {
    this.fuelTypelist = this.fuelTypelist1
  },
  methods: {
    //触发校验
    triggerSingleFieldValidate(refName) {
      this.$refs[refName].onFieldChange()
    },
    //字符串中小写转大写
    upperCase(str) {
      let arr = str.split('')
      let newStr = ''
      // 通过数组的forEach方法来遍历数组
      arr.forEach(function (value) {
        if (value >= 'a' && value <= 'z') newStr += value.toUpperCase()
        else newStr += value
      })
      this.form.carNo = newStr
    },
    //屏蔽键盘
    hideKeyBorder(e) {
      uni.hideKeyboard()
    },
    //车型选择
    carTypeconfirm(val) {
      this.form.carTypeName = val[0].label
      this.form.carType = val[0].value
    },
    //排放标准选择
    emissionStandardsconfirm(val) {
      this.form.emissionName = val[0].label
      this.form.emission = val[0].value
      this.form.fuelTypeName = ''
      this.form.fuelType = ''
      if (val[0].label == '新能源') {
        this.fuelTypelist = this.fuelTypelist1.filter(
          (i) => i.label == '电动' || i.label == '天然气'
        )
      } else {
        this.fuelTypelist = this.fuelTypelist1
          .filter((i) => i.label != '电动')
          .filter((i) => i.label != '天然气')
      }
    },
    //燃料类型下拉开启
    fuelTypeShowFc() {
      if (this.form.emissionValue) {
        this.fuelTypeShow = true
      } else {
        this.$api.msg('请先选择排放标准')
      }
    },
    //燃料类型
    fuelTypeconfirm(val) {
      this.form.fuelTypeName = val[0].label
      this.form.fuelType = val[0].value
    },
    //车头行驶证上传
    headLicensesuccess(data, index, lists, name) {
      if (data.code == '0') {
        this.form.headLicense = data.result.imgUrl
        this.form.carNo = data.result.licensePlateNumber
        setTimeout(() => {
          this.triggerSingleFieldValidate('carNo')
        })
        this.headLicense = true
      } else {
        this.$refs.uUpload1.lists = []
        setTimeout(() => {
          this.$api.msg(data.message)
        }, 200)
      }
    },
    //车头行驶证上传删除
    headLicenseremove(data, index, lists, name) {
      this.form.headLicense = ''
      this.headLicense = false
    },
    //挂车行驶证上传
    attachLicensesuccess(data, index, lists, name) {
      if (data.code == '0') {
        this.form.attachLicense = data.result.imgUrl
        this.form.attachNo = data.result.licensePlateNumber
        setTimeout(() => {
          this.triggerSingleFieldValidate('attachNo')
        })
        this.attachLicenseEditable = true
      } else {
        this.$refs.uUpload2.lists = []
        setTimeout(() => {
          this.$api.msg(data.message)
        }, 200)
      }
    },
    //挂车行驶证上传删除
    attachLicenseremove(data, index, lists, name) {
      this.form.attachLicense = ''
      this.attachLicenseEditable = false
    },
    //车头运输证上传
    headTranssuccess(data, index, lists, name) {
      if (data.code == '0') {
        this.form.headTrans = data.result
        this.headTransEditable = true
      } else {
        this.form.headTrans = ''
        setTimeout(() => {
          this.$api.msg(data.message)
        }, 200)
      }
    },
    //车头运输证上传删除
    headTransremove(data, index, lists, name) {
      this.form.headTrans = ''
      this.headTransEditable = false
    },
    //挂车运输证上传
    attachTranssuccess(data, index, lists, name) {
      if (data.code == '0') {
        this.form.attachTrans = data.result
        this.attachTransEditable = true
      } else {
        this.form.attachTrans = ''
        setTimeout(() => {
          this.$api.msg(data.message)
        }, 200)
      }
    },
    //挂车运输证上传删除
    attachTransremove(data, index, lists, name) {
      this.form.attachTrans = ''
      this.attachTransEditable = false
    },
    //环保清单上传
    eProtectionSheetsuccess(data, index, lists, name) {
      if (data.code == '0') {
        this.form.eProtectionSheet = data.result
        this.eProtectionSheetEditable = true
      } else {
        this.form.eProtectionSheet = ''
        setTimeout(() => {
          this.$api.msg(data.message)
        }, 200)
      }
    },
    //环保清单上传删除
    eProtectionSheetremove(data, index, lists, name) {
      this.form.eProtectionSheet = ''
      this.eProtectionSheetEditable = false
    },
    //车辆照片上传
    carPhotosuccess(data, index, lists, name) {
      if (data.code == '0') {
        this.form.carPhoto = data.result
        this.carPhotoEditable = true
      } else {
        this.form.carPhoto = ''
        setTimeout(() => {
          this.$api.msg(data.message)
        }, 200)
      }
    },
    //车辆照片上传删除
    carPhotoremove(data, index, lists, name) {
      this.form.carPhoto = ''
      this.carPhotoEditable = false
    },
    //上传失败
    testerror(res, index, lists, name) {
      this.$api.msg('上传失败')
    },
    // 提示
    showToast(title, type) {
      this.$refs.uToast.show({
        title,
        type: type || 'error',
      })
    },
    async validateRepeatBinding() {
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          const { code, message, result } = await this.$u.get(
            `/freight-business/logisticsCar/checkCarExist?carNo=${this.form.carNo}`
          )
          if (code === '0') {
            if (result == true) {
              this.repeatBindingShow = false
              this.submit()
            } else {
              this.repeatBindingShow = true
            }
          } else {
            this.$api.msg(message)
          }
        } else {
          this.$api.msg('请填写相关信息')
        }
      })
    },
    //提交
    submit() {
      if (this.repeatBindingShow == true) {
        this.repeatBindingShow = false
      }
      let attachedPhotos = {
        headLicense: this.form.headLicense,
        attachLicense: this.form.attachLicense,
        headTrans: this.form.headTrans,
        attachTrans: this.form.attachTrans,
        eProtectionSheet: this.form.eProtectionSheet,
        carPhoto: this.form.carPhoto,
      }
      this.form.attachedPhotos = JSON.stringify(attachedPhotos)
      this.postData(this.form)
    },
    // 提交数据
    postData(data) {
      let photoList = [
        'headLicense',
        'attachLicense',
        'headTrans',
        'attachTrans',
        'eProtectionSheet',
        'carPhoto',
      ]
      let tagShow = true
      photoList.forEach((item) => {
        if (!data[item] || data[item] == undefined) {
          tagShow = false
        }
      })
      let obj = {
        ...data,
      }
      if (tagShow) {
        this.submitData(obj)
      } else {
        this.$api.msg('部分图片未上传')
      }
    },
    // 车辆排放标准数组
    async getEmissionStandardsData() {
      const { code, result, message } = await this.$u.get(
        '/freight-auth/dictValue/type/vehicle_emissions'
      )
      if (code === '0') {
        this.emissionStandardslist = result.map((item) => {
          return {
            label: item.labelDefault,
            value: item.value,
          }
        })
      } else {
        this.$api.msg(message)
      }
    },
    // 车辆添加提交
    async submitData(val) {
      const { code, result, message } = await this.$u.post(
        '/freight-business/driver/car/add',
        val
      )
      if (code === '0') {
        this.$api.msg('车辆添加成功')
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/tabbar/my/my',
          })
        }, 200)
      } else {
        this.$api.msg(message)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.content {
  background-color: rgb(238, 238, 239);
  padding: 16rpx;
  width: 100%;
  ::v-deep .u-model {
    background-image: linear-gradient(#ffe5e5, #fff);
  }

  .top-box {
    .width-50 {
      flex: 1;
    }
  }
}
.form-title {
  font-weight: 600;
  font-size: 32rpx;
  padding: 16rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.default-check {
  display: flex;
  color: #2979ff;
  font-size: 30rpx;
  // justify-content: space-between;
  align-items: center;
}
.form-item-box {
  background: red;
}
.vehiclemanagement-index-btn {
  width: 100%;
}
.card-box {
  background: white;
  margin-top: 24rpx;
  border-radius: 10rpx;
  padding: 24rpx 24rpx 0;
  .card-title-box {
    font-size: 28rpx;
    font-weight: 600;
  }
  .card-icon-box {
    margin-left: 6rpx;
    position: relative;
    view:nth-child(1) {
      width: 20rpx;
      height: 20rpx;
      border-radius: 50%;
      background: #57a3ff;
      position: absolute;
      top: -12rpx;
      left: 10rpx;
      z-index: 1;
    }
    view:nth-child(2) {
      width: 20rpx;
      height: 20rpx;
      border-radius: 50%;
      background: #add3ff;
      position: absolute;
      top: -6rpx;
      left: 20rpx;
    }
  }
}
.uUpload-box {
  /deep/.u-list-item {
    // background-image: url('https://minio.wskjwl.com/uipicture/xingshizheng.png');
    background-size: 100% 100%;
    background-position: center;
    background-repeat: no-repeat;
  }
}
</style>
